<?php

/**
 * +----------------------------------------------------------------------
 * | 润憬商城系统 [ 高性价比的通用商城系统 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2022~2023 https: *www.honc.fun All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * +----------------------------------------------------------------------
 * | Author: 润憬科技 Hon(陈烁临) <2275604210@qq.com>
 * +----------------------------------------------------------------------
 */

namespace app\common\event;


use app\common\service\Message as MessageService;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\OrderSource as OrderSourceEnum;

class OrderPaySuccess
{
  // 订单信息
  private $order;

  // 订单类型
  private $orderType;

  // 当前商城ID
  private $storeId;

  /**
   * 订单来源回调业务映射类
   * @var array
   */
  protected $sourceCallbackClass = [
    OrderSourceEnum::MAIN => \app\api\service\main\order\PaySuccess::class,
  ];

  /**
   * 执行句柄
   * @param array $params
   * @return bool
   */
  public function handle(array $params)
  {
    // 解构赋值: 订单模型、订单类型
    ['order' => $order, 'orderType' => $orderType] = $params;
    // 设置当前类的属性
    $this->setAttribute($order, $orderType);
    // 订单公共事件
    $this->onCommonEvent();
    // 订单来源回调业务
    $this->onSourceCallback();
    return true;
  }

  /**
   * 设置当前类的属性
   * @param $order
   * @param int $orderType
   */
  private function setAttribute($order, $orderType = OrderTypeEnum::ORDER)
  {
    $this->order = $order;
    $this->storeId = $this->order['store_id'];
    $this->orderType = $orderType;
  }

  /**
   * 订单公共业务
   */
  private function onCommonEvent()
  {
    // 发送消息通知
    MessageService::send('order.payment', [
      'order' => $this->order,
      'order_type' => $this->orderType,
    ], $this->storeId);
  }

  /**
   * 订单来源回调业务
   * @return bool
   */
  private function onSourceCallback()
  {
    if (!isset($this->order['order_source'])) {
      return false;
    }
    if (!isset($this->sourceCallbackClass[$this->order['order_source']])) {
      return false;
    }
    $class = $this->sourceCallbackClass[$this->order['order_source']];
    return !is_null($class) ? (new $class)->onPaySuccess($this->order) : false;
  }
}
